package cn.longwi.lwse.controller;


import cn.longwi.lwse.domain.FormData;
import cn.longwi.lwse.domain.RespResult;
import cn.longwi.lwse.domain.ResponseCode;
import cn.longwi.lwse.service.LicenseService;
import cn.longwi.lwse.utils.HardwareInfoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LicenseController {

    @Autowired
    private LicenseService licenseService;

    @RequestMapping("license")
    public String license(ModelMap modelMap){
        RespResult respResult = licenseService.hasValidLicense();
        if (respResult.getCode() != ResponseCode.SUCCESS.getCode()){
            String msg = "错误码：" + respResult.getCode() + " 消息：" + respResult.getMsg();
            modelMap.addAttribute("message", msg);
            modelMap.addAttribute("formData", new FormData());
            String hardwareIdentifier = HardwareInfoUtil.getHardwareIdentifier();
            modelMap.addAttribute("hardwareIdentifier", hardwareIdentifier);
            return "license";
        }
        Object licenseInfo = respResult.getData();
        modelMap.addAttribute("license", licenseInfo);
        return "successLicense";
    }

    @PostMapping("submitLicense")
    public String submitLicense(@ModelAttribute("formData") FormData formData, ModelMap modelMap) {
        RespResult respResult = licenseService.registerLicense(formData.getLicenseCode());
        if (respResult.getCode() != ResponseCode.SUCCESS.getCode()){
            String msg = respResult.getCode() + " " + respResult.getMsg();
            modelMap.addAttribute("message", msg);
            String hardwareIdentifier = HardwareInfoUtil.getHardwareIdentifier();
            modelMap.addAttribute("hardwareIdentifier", hardwareIdentifier);
            return "redirect:/license"; // 页面重定向到授权页面
        }
        return "redirect:/license"; // 页面重定向到授权页面
    }
}
